﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using SCFHS.Data;

namespace SCFHS.Views.Searchs
{
    public partial class Search : SysBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string sqlSearch = string.Empty;
            if (!string.IsNullOrEmpty(txtPersonNameToSearch.Text))
            {
                sqlSearch = "PersonName LIKE CONCAT('" + txtPersonNameToSearch.Text + "','%')";
            }
            else if (!string.IsNullOrEmpty(txtOrderNumberToSearch.Text))
            {
                sqlSearch = "OrderNumber LIKE CONCAT('" + txtOrderNumberToSearch.Text + "','%')";
            }
            else if (!string.IsNullOrEmpty(txtClassificationNumber.Text))
            {
                sqlSearch = "OrderClassificationNumber LIKE CONCAT('" + txtClassificationNumber.Text + "','%')";
            }
            BindSearchResult(sqlSearch);

        }

        void BindSearchResult(string sqlSearch)
        {
            DataTable searchResultDt = controller.SearchOnOrder(sqlSearch);

            if (searchResultDt == null || searchResultDt.Rows.Count == 0)
            {
                searchResult.Visible = false;
                return;
            }
            else
            {
                if (searchResultDt.Rows.Count == 1)
                {
                    Session.Remove("searchResult");
                    Session.Add("searchResult", searchResultDt);
                }
                searchResult.Visible = true;
                grdSearchResult.DataSource = searchResultDt;
                grdSearchResult.DataBind();
            }
        }

        protected void btnDetails_Click(object sender, EventArgs e)
        {
            string orderToGet = ((LinkButton)sender).CommandArgument;
            Order resultOrder = null;
            if (Session["searchResult"] != null)
            {
                DataTable searchResultDt = Session["searchResult"] as DataTable;
                resultOrder = controller.ConvertToOrder(searchResultDt);
            }
            else
            {
                if (string.IsNullOrEmpty(orderToGet))
                {
                    return;
                }

                resultOrder = controller.ConvertToOrder(controller.SelectFullOrderDetailsInfo(int.Parse(orderToGet)));

            }
            if (resultOrder == null)
            {
                return;
            }
            Session.Remove("resultOrder");
            Session.Add("resultOrder", resultOrder);
            Response.Redirect("FullOrder.aspx");
        }
    }
}